<?php

namespace app\admin\controller\user;

use app\common\controller\Backend;
use app\common\library\Auth;
use app\admin\model\UserRoseLog;
use app\admin\model\UserAddress;
use app\admin\model\Product;
use app\admin\model\Configuration;
use app\admin\model\User as UserModel;
use app\admin\model\Category;
use app\admin\model\UserOrder;
use app\admin\model\ProductCategory;

/**
 * 会员管理
 *
 * @icon fa fa-user
 */
class User extends Backend
{

    protected $relationSearch = true;
    protected $searchFields = 'id,username,nickname';

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;

    public function _initialize()
    {
        
        parent::_initialize();
        $this->model = model('User');
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams('id,nickname,mobile');
            $list = $this->model
                //->with('group')
                ->where($where)
                ->where(['mobile'=>['neq','']])
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => $v) {
                //邀请人信息
                if($v['invite_user_id']){
                    $v->invite_user_id = '【'.$v['invite_user_id'].'】'.$this->model->where('id',$v['invite_user_id'])->value('nickname');
                }else{
                    $v->invite_user_id = '';
                }
                $v->avatar = $v->avatar ? cdnurl($v->avatar, true) : letter_avatar($v->nickname);
                $v->hidden(['password', 'salt']);
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }
    
    

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $this->token();
        }
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }

        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        $params['mobile'] = str_replace('，',',',$params['mobile']);
        $arr = explode(',',$params['mobile']);
        $configuration = Configuration::find();
        foreach ($arr as $mobile) {
            //创建之前查询手机号是否已经注册
            $user=UserModel::where(array('mobile'=>$mobile,'status'=>['in','1,0']))->find();
            if($user){
                continue;
            }
            $nickname = $this->repetition_nickname('任务用户'.$mobile);
            $token=md5(md5(date("ymdHis").rand(100000,999999)));
            $user=array(
                'mobile'			=>$mobile,
                'rose_money'		=>0,
                'nickname'			=>$nickname,
                'avatar'			=>$configuration['default_avatar'],
                'profile'			=>'',
                'gender'			=>0,
                'birthday'			=>'',
                'city'				=>'',
                'bgimg'				=>$configuration['default_bgimg'],
                'tags'				=>'',
                'weixin'			=>'',
                'rose_money'		=>0,
                'read_message'		=>0,
                'follow_count'		=>0,
                'fans_count'		=>0,
                'love_count'		=>0,
                'token'				=>$token,
                'last_login_time'	=>time(),
                'add_time'			=>time(),
                'virtual_status'    =>2
            );
            UserModel::insert($user);
        }
        $this->success('操作成功');
    }
    //检查昵称是否重复
    public function repetition_nickname($nickname,$suffix = ''){
        $user = UserModel::where(['status'=>1,'nickname'=>$nickname.$suffix])->find();
        if($user){ // 有重复值
            if($suffix==''){
                $suffix = 'a';
            }elseif($suffix=='a'){
                $suffix = 'b';
            }elseif($suffix=='b'){
                $suffix = 'c';
            }elseif($suffix=='c'){
                $suffix = 'd';
            }
            return $this->repetition_nickname($nickname,$suffix);
        }else{
            return $nickname.$suffix;
        }
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        if ($this->request->isPost()) {
            $this->token();
        }
        $row = $this->model->where('id',$ids)->find();
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        $row = $this->model->where('id',$ids)->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = $row->where(['id'=>$ids])->update($params);
        if (!$result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        $row = $this->model->where('id',$ids)->find();
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        Auth::instance()->delete($row['id']);
        $this->success();
    }
    /**
     * 设置是否监管
     */
    public function setSupervise($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->get("id");
        UserModel::where(['id'=>$ids])->update(['is_supervise'=>$this->request->get('is_supervise')]);
        $this->success();
    }
    

    //余额充值
    public function balance( $ids = ""){
        $ids = $ids ? $ids : $this->request->post("ids");
        $row = $this->model->where('id',$ids)->find();

        if ($this->request->isPost()) {
            $this->token();
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                try {
                    $data['rose_money'] = $row['rose_money'] + $params['rose'];
                    $result = $row->allowField(true)->save($data);
                    if ($result !== false) {
                        UserRoseLog::insert(['user_id'=>$row['id'],'type'=>24,'title'=>'后台变动金额','add_time'=>time(),'rose_money'=>$params['rose']]);
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }


        $this->assign('row',$row);
        return $this->view->fetch();
    }

     /**
     * 财务明细
     */
    public function finance( $ids = "" )
    {
        $ids = $ids ? $ids : $this->request->post("ids");
        $this->assignconfig('ids', $ids);
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = UserRoseLog::where(['user_id'=>$ids])
                ->order('add_time desc')
                ->paginate($limit);
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

     /**
     * 地址管理
     */
    public function address( $ids = "" )
    {
        $ids = $ids ? $ids : $this->request->post("ids");
        $this->assignconfig('ids', $ids);
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = UserAddress::where(['user_id'=>$ids])
                ->order('add_time desc')
                ->paginate($limit);
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 产品管理
     */
    public function product( $ids = "" )
    {
        $ids = $ids ? $ids : $this->request->post("ids");
        $this->assignconfig('ids', $ids);
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams('id,title','',new Product());
            $list = Product::where(['user_id'=>$ids])
                ->where($where)
                ->order('add_time desc')
                ->paginate($limit);
            foreach ($list as $k => $v) {
                //获取分类名称
                $category =  Category::where(['id'=>$v['category_id']])->find();
                //分类名称
                $list[$k]['category'] = $category['name'];
                $imgs = explode(',',$v['video_img']);
                $list[$k]['video_img'] = $imgs[0];
                if(strstr($list[$k]['video_img'], 'mp4')){
                    $list[$k]['video_img'] =  $list[$k]['video_img'].'?x-oss-process=video/snapshot,t_1000,m_fast,ar_auto';
                }
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

     /**
     * 订单管理
     */
    public function order( $ids = "" )
    {
        $ids = $ids ? $ids : $this->request->post("ids");
        $this->assignconfig('ids', $ids);
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams('id,order_id','',new UserOrder());
            
            $where1 = (array)$where;
            $where = (array)$where;
            $where['shop_id'] = $ids;
            $where['status'] = ['neq',-1];
            $where1['status'] = ['neq',-1];
            $where1['user_id'] = $ids;
            $list = UserOrder::where($where)
                ->whereOr(function($query) use ($where1){
                    $query->where($where1);
                })
                ->order('add_time desc')
                ->paginate($limit);
            foreach ($list as $k => $v) {
                if($v['user_id'] == $ids){
                    $v['price'] = $v['price']*-1;
                }
                $product =  Product::where(['id'=>$v['product_id']])->find();
                $imgs = explode(',',$product['video_img']);
                $list[$k]['peisong'] = $product['peisong'];
                $list[$k]['video_img'] = $imgs[0];
                if(strstr($list[$k]['video_img'], 'mp4')){
                    $list[$k]['video_img'] =  $list[$k]['video_img'].'?x-oss-process=video/snapshot,t_1000,m_fast,ar_auto';
                }
                //商品名称
                $list[$k]['product_name'] = $product['title'];
                //商家id
                $list[$k]['shop_tel'] = UserModel::where('id',$product['user_id'])->value('mobile'); //$product['phone'];
                //if(!$list[$k]['address_tel']){
                    $list[$k]['address_tel'] = UserModel::where('id',$v['user_id'])->value('mobile');
                //}
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

}
